﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Text;

namespace DatabaseLockSample.Samples
{
    public class PurchaseGirlSample
    {
        public static void Sample()
        {
            Console.WriteLine("请输入您的名字：");
            var name = Console.ReadLine();
            var id = 1;
            var bf = string.Empty;
            var rowVersion = new byte[] { };
            using (var myConn = new SqlConnection(Config.ConnString))
            {
                myConn.Open();
                using (var tx = myConn.BeginTransaction())
                {
                    //var selSql = "select * from [Girl] with(xLock,ROWLOCK) where Id=@Id";
                    var selSql = "select * from [Girl] where Id=@Id";
                    using (var cmd = new SqlCommand(selSql, myConn, tx))
                    {
                        cmd.Parameters.Add(new SqlParameter("Id", id));
                        using (var dr = cmd.ExecuteReader())
                        {
                            while (dr.Read())
                            {
                                bf = dr["BF"].ToString();
                                 rowVersion = dr["RowVersion"] as byte[];
                                //rowVersionStr = $"0x{BitConverter.ToString(rowVersion as byte[]).Replace("-","")}";
                            }
                        }
                    }
                    if (!string.IsNullOrEmpty(bf))
                    {
                        if (bf.Equals(name.Trim()))
                        {
                            Console.WriteLine("别调皮了，已经是你的人了！");
                        }
                        else
                        {
                            Console.WriteLine($"已经是{bf}的人了！");
                        }
                    }
                    else
                    {
                        var updateSql = "update [Girl] Set BF=@BF where Id=@Id and RowVersion=@RowVersion";
                        using (var cmd01 = new SqlCommand(updateSql, myConn, tx))
                        {
                            cmd01.Parameters.Add(new SqlParameter("BF", name.Trim()));
                            cmd01.Parameters.Add(new SqlParameter("Id", id));
                            cmd01.Parameters.Add(new SqlParameter("RowVersion", rowVersion));
                            cmd01.ExecuteNonQuery();
                        }
                    }
                    tx.Commit();
                }
            }
        }
    }
}
